local M = {}
local config = require("config.apps")
local ui = require("modules.app-launcher.ui")
local hotkeyUtils = require("utils.hotkey")

local numberHotkeys = {}
local escapeHotkey = nil

local function launchApp(key)
    for _, app in ipairs(config) do
        if app.id == key then
            hs.application.launchOrFocusByBundleID(app.bundleID)
            break
        end
    end
    -- 确保在启动应用后清理热键
    M.cleanupHotkeys()
end

function M.setupHotkeys()
    -- 先清理之前可能存在的热键
    M.cleanupHotkeys()

    -- 为每个应用绑定对应的快捷键
    for i, app in ipairs(config) do
        if app.id ~= "" then
            numberHotkeys[i] = hotkeyUtils.bindHotkey({}, app.id, function()
                launchApp(app.id)
                ui.hideLauncher()
            end)
            numberHotkeys[i]:enable()
        end
    end

    -- 绑定ESC键
    escapeHotkey = hotkeyUtils.bindHotkey({}, "escape", function()
        ui.hideLauncher()
        M.cleanupHotkeys()
    end)
    escapeHotkey:enable()
end

function M.cleanupHotkeys()
    -- 确保清理所有热键
    if numberHotkeys then
        for _, hotkey in pairs(numberHotkeys) do
            if hotkey then
                hotkey:delete()
            end
        end
        numberHotkeys = {}
    end

    if escapeHotkey then
        escapeHotkey:delete()
        escapeHotkey = nil
    end
end

return M